import { Component } from 'react'

class ErrorBoundary extends Component {
  /* eslint-disable-next-line */
  state = {
    hasError: false,
  }

  static getDerivedStateFromError(error) {
    return { hasError: true }
  }

  componentDidCatch(error) {
    // 可以做一些错误的打印
    console.log(error)
  }

  handleRestry = () => {
    this.setState({ hasError: false })
  }

  render() {
    const { hasError } = this.state
    const { children } = this.props
    if (hasError) {
      return (
        <p>
          <span>对不起出错了</span>
          <button onClick={this.handleRestry} type="button">请重试</button>
        </p>
      )
    }
    return children()
  }
}

export default ErrorBoundary
